package com.hedl.classroom.controller;

import com.alipay.api.AlipayApiException;
import com.hedl.classroom.base.exception.OnlinecClassroomException;
import com.hedl.classroom.dto.AddOrderDto;
import com.hedl.classroom.dto.PayRecordDto;
import com.hedl.classroom.service.OrderPaymentService;
import com.hedl.classroom.service.OrderService;
import com.hedl.classroom.utils.SecurityUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * @author Big Watermelon
 * @description 订单相关的接口
 * @date 2023/12/18/11:03
 */
@Api(value = "订单支付接口",tags = "订单支付接口")
@Slf4j
@Controller
public class OrderController {

    @Resource
    private OrderService orderService;

    @Resource
    private OrderPaymentService orderPaymentService;
    @ApiOperation("生成支付二维码")
    @PostMapping("/generatepaycode")
    @ResponseBody
    public PayRecordDto generatePayCode(@RequestBody AddOrderDto addOrderDto){

        SecurityUtil.XcUser user = SecurityUtil.getUser();
        if (user == null){
            OnlinecClassroomException.cast("请登录！");
        }
        //用户id
        String userId = user.getId();

        //调用service,完成插入订单信息，插入支付记录，生成支付二维码
        PayRecordDto payRecordDto = orderService.createOrder(userId, addOrderDto);

        return payRecordDto;
    }

    @ApiOperation("扫码下单接口")
    @GetMapping("/requestpay")
    public void requestpay(String payNo,HttpServletResponse httpServletResponse) throws AlipayApiException, IOException {
        orderPaymentService.requestpay(payNo,httpServletResponse);
    }

    @ApiOperation("查询支付结果")
    @GetMapping("/payresult")
    @ResponseBody
    public PayRecordDto payresult(String payNo) throws AlipayApiException {
        PayRecordDto payresult = orderPaymentService.payresult(payNo);
        return payresult;
    }

    @ApiOperation("接收支付结果通知")
    @PostMapping("/paynotify")
    public void receivenotify(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, AlipayApiException {
        orderPaymentService.receivenotify(httpServletRequest,httpServletResponse);
    }
}
